package com.telink.lt.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.telink.lt.R
import com.telink.lt.ServiceApi
import com.telink.lt.adapter.FileAdapter
import com.telink.lt.ui.file.FileSelectActivity
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import kotlinx.coroutines.flow.collect
class DownLoadActivity : AppCompatActivity() {
    var clickData:String? = null
    var adapter = FileAdapter()
    var title :String?= null
    @SuppressLint("ResourceAsColor")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_down_load)
        DialogX.init(this)

        /**
         * 设置 toolBar
         */

        val mToolbar = findViewById<View>(R.id.toolbar) as Toolbar
        // 该属性必须在setSupportActionBar之前 调用
        mToolbar.title = "请选择升级文件"
        setSupportActionBar(mToolbar)
        val rvFile = findViewById<RecyclerView>(R.id.rvFile)
        val layoutManager = LinearLayoutManager(this)
        rvFile.layoutManager = layoutManager
        val itemDecoration = DividerItemDecoration(
            this,
            LinearLayoutManager.VERTICAL
        )
        rvFile.addItemDecoration(itemDecoration)
        rvFile.adapter = adapter
        var build = Retrofit.Builder().baseUrl("https://www.bianjiaojing.com/")
            .addConverterFactory(GsonConverterFactory.create()).build()
        val retrofit = build.create(ServiceApi::class.java)
        retrofit.get(5).enqueue(object :Callback<otaBean>{
            override fun onResponse(call: Call<otaBean>, response: Response<otaBean>) {
                if (response.isSuccessful){
                    var body = response.body()
                    var data = body?.data
                    adapter.setList(data)
                    var toString = data.toString()
                    Log.e("TAG", "onResponse: " + toString )
                }
            }

            override fun onFailure(call: Call<otaBean>, t: Throwable) {

                Toast.makeText(this@DownLoadActivity, t.message, Toast.LENGTH_LONG).show()
            }
        })

        adapter.setOnItemClickListener { adapter, view, position ->
//            download(this, url = (adapter.data[position]as BinBean).name)
            clickData = (adapter.data[position] as Data).adUrl
            title = (adapter.data[position] as Data).adTitle
            download(this, url = clickData!!)
//            requestPermission()
        }
    }
//
//    @InternalCoroutinesApi
//    fun requestPermission() {
//        requestMutiPermissionLauncher.launch(
//            arrayOf(
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_EXTERNAL_STORAGE
//            )
//        )
//    }

    @InternalCoroutinesApi
    val requestMutiPermissionLauncher =
        registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { result: Map<String, Boolean> ->
            if (result[Manifest.permission.WRITE_EXTERNAL_STORAGE] == true && result[Manifest.permission.READ_EXTERNAL_STORAGE] == true) {

            } else {
                Toast.makeText(MainActivity@ this, "拒绝了权限", Toast.LENGTH_LONG).show()
            }
        }

    fun download(context: Context, url: String) {
        val time = System.currentTimeMillis()
        LogUtil.d("time1:${time}")

        val file2 = getTargetParentFile(context)
        lifecycleScope.launch {
            DownloadGO.download(
                url = url,
                targetParent = file2.path
            ).collect {
                when (it) {
                    is DownloadStatus.onFail -> {

                        Toast.makeText(this@DownLoadActivity, "下载失败"+  it.error, Toast.LENGTH_LONG).show()
                    }
                    is DownloadStatus.onProgress -> {
                        val pb = (it.progress?.div(100f))
                        WaitDialog.show("正在下载" + (it.progress) + "%", pb!!.toFloat())

                    }
                    is DownloadStatus.onSuccess -> {
                        Log.e("TAG", "downloadSuccess: ")
                        TipDialog.show("下载完成", WaitDialog.TYPE.SUCCESS, 500)
                        val intent = Intent()
                        Log.e("TAG", "absolutePath: "+ it.file?.absolutePath)
                        intent.putExtra(FileSelectActivity.KEY_RESULT,it.file?.absolutePath)
                        intent.putExtra("title",title)
                        setResult(RESULT_OK, intent)
                        finish()

                    }
                    else -> {

                    }
                }
            }

            LogUtil.d("处理完成")
        }
    }

    fun getTargetParentFile(context: Context): File {
        val file0 = context.externalCacheDir.toString()
        val file1 = File("${file0}/MyDownload")
        if (!file1.exists() || !file1.isDirectory) {
            file1.mkdirs()
        }
        return file1
    }
}



